package phone.book;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class edit_contact extends Activity{
	 
	@Override
	public void onCreate(Bundle savedInstanceState) {
					super.onCreate(savedInstanceState);
					setContentView(R.layout.addcontact);
					long id = getIntent().getExtras().getLong("contactId");
					ContentResolver cr = getContentResolver();
					String id1 = BaseColumns._ID;
					String id2= Long.toString(id);
					Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,id1+"="+id2, null, null);
					String name = null;
					String hasPhoneNumber;
					String phoneNumber = null;
					while (cur.moveToNext()) {
						name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
						
						hasPhoneNumber = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));				        
						if (Integer.parseInt(hasPhoneNumber) > 0) {
			                // Query the table
			                 cur = getContentResolver().query(Phone.CONTENT_URI,
			                         null, Phone.CONTACT_ID + "=?", new String[] {cur.getString(cur.getColumnIndex(BaseColumns._ID)) },
			                         null);
			                 int PhoneIdx = cur.getColumnIndex(Phone.DATA);			                
			                 // Get the phone numbers from the contact
			                 if (cur.moveToFirst()) {			                      
			                     // Get a phone number
			                     phoneNumber =cur.getString(PhoneIdx);			        
			                 }
			             } else {
			              Toast.makeText(this, "This contact doesn't have a phone number",
			                         Toast.LENGTH_LONG).show();
			             
			             }
					}
					final EditText fname = (EditText) findViewById(R.id.editText1);
					final EditText lname = (EditText) findViewById(R.id.editText2);
					final EditText phone = (EditText) findViewById(R.id.editText3);
					final Button button1 = (Button) findViewById(R.id.button1);
					final Button button2 = (Button) findViewById(R.id.button2);	
					String[] words = name.split(" "); 
					if(words.length==1)
					{
						fname.setText(words[0]);
						lname.setText("");
					}
					if(words.length==2)
					{
						fname.setText(words[0]);
						lname.setText(words[1]);
					}
					if(words.length==0)
					{
						fname.setText("");					
						lname.setText("");
					}
					if(phoneNumber!=null)
						phone.setText(phoneNumber);
					else
						phone.setText("");
					final Context c = this;
					button1.setOnClickListener(new View.OnClickListener() {             
						public void onClick(View v) {                 // Perform action on click             
							
							final String DisplayName =fname.getText().toString()+" "+lname.getText().toString();
							final String MobileNumber = phone.getText().toString();
							
							long id = getIntent().getExtras().getLong("contactId");
					        String id2= Long.toString(id);
					        
					       
					        contactDetails cd = new contactDetails();
					        Log.d("id to delete", id2);
					        cd.deleteContact(id2,c);
					        Log.d("New name", DisplayName);
					        Add_contact ac = new Add_contact();
					        ac.addContact(DisplayName, MobileNumber,c);
					        
					        Intent i=new Intent(getApplicationContext(),PhonebookActivity.class);						
							startActivityForResult(i, 0);
					        /*ContentValues values = new ContentValues();
							values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,DisplayName);
							values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber);
							//Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
							// Asking the Contact provider to create a new contact
							//String[] update = {"DISPLAY_NAME","NUMBER"};
							ContentResolver cr = getContentResolver();
							Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,id1+"="+id2, null, null);
							while (cur.moveToNext()) { 
								try{ 
									String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
									
									Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
									System.out.println("The uri is " + uri.toString());
									getContentResolver().update(uri, values, id1+"="+id2,null);                    
							}                      
							catch (Exception e)                      
							{                                        
								e.printStackTrace();                         
								Toast.makeText(edit_contact.this, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();                     
							} */
						/*	 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); 
							 ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI).withSelection(Data._ID + "=?", new String[]{String.valueOf(id1)}).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DisplayName).build());
							 try {
								getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
							} catch (RemoteException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (OperationApplicationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}*/

							finish();
						}       
						
					});
					button2.setOnClickListener(new View.OnClickListener() {             
						public void onClick(View v) {                 // Perform action on click             
								finish();
							}         
					});
					
	}
}